<template>
  <div class="w-screen h-screen bg-white px-[346px]">
    <!-- 本地预警区域 -->
    <div
      class="w-[640px] h-[224.97px] pt-[45px] pb-[55px] bg-gradient-to-t from-red-100 to-blue-100 rounded-[20px] flex flex-col items-center justify-center"
    >
      <div v-if="localWarning.length === 0" class="text-center">
        <img src="/public/warning-no-data.png" alt="" class="h-[92.95px]">
        <p class="mt-4 text-lg font-medium">暂无预警</p>
      </div>
      <div v-else class="px-[20px] text-center">
        <p class="mt-4 text-sm font-medium">{{ localWarning[0].title }}</p>
        <p class="mt-1 text-xs text-gray-600">
          {{ formatTime(localWarning[0].pubTime) }} ·
          {{ localWarning[0].sender }}
        </p>
        <div class="mt-4 text-xs text-gray-600">
          {{ localWarning[0].text }}
        </div>
      </div>
    </div>

    <!-- 最新预警信息区域 -->
    <div
      class="w-[640px] bg-white border border-gray-200 rounded-xl shadow-sm overflow-hidden mt-8"
    >
      <div class="px-6 py-4 bg-gray-50 border-b border-gray-200">
        <h2 class="text-lg font-semibold text-gray-800 text-center">
          附近预警
        </h2>
      </div>
      <div class="divide-y divide-gray-200">
        <div
          v-for="warning in nearbyWarnings"
          class="flex items-center justify-between p-4 hover:bg-gray-50 transition-colors cursor-pointer"
        >
          <span class="text-sm font-medium text-gray-700">
            {{ warning.name }}，{{ warning.province }}
          </span>
          <div class="flex items-center justify-center space-x-3 w-[100px]">
            <span class
              :class="`flex items-center justify-center w-8 h-5 rounded-full text-xs font-medium text-center ${
                warning.severityColor === 'Yellow'
                  ? 'bg-yellow-500 text-white'
                  : warning.severityColor === 'Blue'
                  ? 'bg-blue-500 text-white'
                  : warning.severityColor === 'Red'
                  ? 'bg-red-500 text-white'
                  : warning.severityColor === 'Orange'
                  ? 'bg-orange-500 text-white'
                  : 'bg-gray-500 text-white'
              }`"
            >
              {{ warning.level }}
            </span>
          </div>
          <span class="text-sm font-medium text-gray-700">{{
              warning.typeName
            }}</span>
        </div>
      </div>
    </div>

    <!-- 数据来源 -->
    <div class="mt-6 text-xs text-gray-500">
      预警数据来源：国家预警信息发布中心
    </div>
  </div>
</template>

<script setup>
import axios from "axios";
import { ref } from "vue";

const localWarning = ref([]);
const nearbyWarnings = ref([]);
const userLatitude = ref(null);
const userLongitude = ref(null);

// 获取本地预警
async function fetchLocalWarning(longitude, latitude) {
  const host = "https://p76yvxv44n.re.qweatherapi.com";
  const token =
    "Bearer eyJhbGciOiJFZERTQSIsImtpZCI6Iks0NUY1R0pRTVAifQ.eyJzdWIiOiI0OVRORjZRRUpWIiwiaWF0IjoxNzU3NTcwODgyLCJleHAiOjE3NTc2NTcyODJ9.tgyV0Ric5fuBRXxJjsF-p9k9qafhmprj7L-49FibuLDxj6iWMUh4VAjYrC7UJ-kFpo8kawH-2OLa20SI1h-ICQ";

  try {
    const response = await axios.get(`${host}/v7/warning/now`, {
      params: { location: `${longitude},${latitude}` },
      headers: { Authorization: token },
    });

    if (response.data.warning && response.data.warning.length > 0) {
      localWarning.value = [response.data.warning[0]];
    }
  } catch (error) {
    console.error("获取本地预警失败:", error);
  }
}


// 获取附近预警
async function fetchNearbyWarnings(lon, lat) {
  const host = "https://p76yvxv44n.re.qweatherapi.com";
  const token =
    "Bearer eyJhbGciOiJFZERTQSIsImtpZCI6Iks0NUY1R0pRTVAifQ.eyJzdWIiOiI0OVRORjZRRUpWIiwiaWF0IjoxNzU3NTcwODgyLCJleHAiOjE3NTc2NTcyODJ9.tgyV0Ric5fuBRXxJjsF-p9k9qafhmprj7L-49FibuLDxj6iWMUh4VAjYrC7UJ-kFpo8kawH-2OLa20SI1h-ICQ";

  try {
    const listResponse = await axios.get(`${host}/v7/warning/list`, {
      params: { range: "cn" },
      headers: { Authorization: token },
    });

    if (listResponse.data.code !== "200") {
      nearbyWarnings.value = [];
      return;
    }

    const locationIds = listResponse.data.warningLocList
      .map((loc) => loc.locationId) //注释：获取预警信息列表中的前10个locationId
      .slice(0, 10);

    axios
      .all(
        locationIds.map((id) =>
          axios.all([
            axios.get(`${host}/v7/warning/now`, {
              params: { location: id },
              headers: { Authorization: token },
            }),
            axios.get(`/api/geo/v2/city/lookup`, {
              params: { location: id },
              headers: { Authorization: token },
            }),
          ])
        )
      )
      .then(function (responses) {
        console.log(responses);
        const detailedWarnings = [];
        responses.forEach((res, index) => {
          const warningRes = res[0]; // 预警详情
          const geoRes = res[1]; // 地理位置

          if (warningRes.data.warning && warningRes.data.warning.length > 0) {
            const warning = warningRes.data.warning[0];
            const provinceName = geoRes.data.location?.[0]?.adm1 || "未知";
            const cityName =
              geoRes.data.location?.[0]?.name ||
              listResponse.data.warningLocList.find(
                (l) => l.locationId === locationIds[index]
              )?.name ||
              "未知";

            console.log("severity:", warning.severity); 
            console.log("severityColor:", warning.severityColor); 

           
            const severityToLevel = {
              Extreme: "红",
              Severe: "橙",
              Moderate: "黄",
              Minor: "蓝",
            };
            const level = severityToLevel[warning.severity] || "未知";

            detailedWarnings.push({
              ...warning,
              province: provinceName,
              name: cityName,
              locationId: locationIds[index],
              level: level,
            });
          }
        });

        // 过滤距离
        let filteredWarnings = [];

        if (lon && lat) {
          filteredWarnings = detailedWarnings.filter((warning) => {
            if (!warning.lat || !warning.lon) return false;
            const dist = calculateDistance(lat, lon, warning.lat, warning.lon);
            return dist <= 500;
          });
        } else {
          filteredWarnings = detailedWarnings.slice(0, 10);
        }

        // 排序
        filteredWarnings.sort((a, b) => {
          const severityOrder = { red: 4, orange: 3, yellow: 2, blue: 1 };
          return severityOrder[b.severity] - severityOrder[a.severity];
        });

        nearbyWarnings.value = filteredWarnings;
      })
      .catch((error) => {
        console.error("获取附近预警失败:", error);
        nearbyWarnings.value = [];
      });

    // 注意：这里不能使用 async/await，因为 axios.all 是 Promise.all
    // 所以我们只能在 .then() 中处理结果
  } catch (error) {
    console.error("获取附近预警失败:", error);
    nearbyWarnings.value = [];
  }
}

// 时间格式化
function formatTime(timeStr) {
  if (!timeStr) return "";
  const date = new Date(timeStr);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "short",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}



// 计算两点间距离（单位：公里）
function calculateDistance(lat1, lon1, lat2, lon2) {
  const R = 6371; // 地球半径（公里）
  const dLat = ((lat2 - lat1) * Math.PI) / 180;
  const dLon = ((lon2 - lon1) * Math.PI) / 180;
  const a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos((lat1 * Math.PI) / 180) *
      Math.cos((lat2 * Math.PI) / 180) *
      Math.sin(dLon / 2) *
      Math.sin(dLon / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  return R * c;
}

// 初始化定位
window.navigator.geolocation.getCurrentPosition(
  (position) => {
    userLatitude.value = position.coords.latitude.toFixed(2);
    userLongitude.value = position.coords.longitude.toFixed(2);

    fetchLocalWarning(userLongitude.value, userLatitude.value);
    fetchNearbyWarnings();
  },
  (error) => {
    console.log("定位失败:", error);
    setTimeout(() => {
      fetchNearbyWarnings();
    }, 500);
  },
  { enableHighAccuracy: true }
);
</script>
